package net.pws.oos.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.pws.common.jackson.JsonUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.common.util.StringUtils;
import net.pws.oos.biz.BizException;
import net.pws.oos.biz.model.Indicator;
import net.pws.oos.biz.model.IndicatorValue;
import net.pws.oos.biz.model.Phone;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.IndicatorFinder;
import net.pws.oos.biz.query.PhoneQuery;
import net.pws.oos.biz.query.parameter.IndicatorQueryParameter;
import net.pws.oos.biz.query.parameter.IndicatorValueQueryParameter;
import net.pws.oos.biz.service.IndicatorService;
import net.pws.oos.security.SecurityUtils;
import net.pws.oos.web.dto.IndicatorDto;
import net.pws.oos.web.dto.IndicatorTreeNodeDto;
import net.pws.oos.web.dto.IndicatorValueDto;
import net.pws.oos.web.dto.TreeNode;
import net.pws.oos.web.dto.UserDto;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 系统管理，组织管理，用户管理，角色管理，权限管理
 */
@Controller
@RequestMapping("/biz/indicator")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class IndicatorAction {
    
    public final transient Log logger = LogFactory.getLog(IndicatorAction.class);
    
    @Autowired
    private IndicatorService indicatorService;
    
    @Autowired
    private IndicatorFinder indicatorFinder;
    
    @Autowired
    private PhoneQuery phoneQuery;
    
    @Autowired
    private EntityManager entityManager;
    
    @RequestMapping("/count.json")
    @ResponseBody
    public Object getIndicatorCount(IndicatorQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            map.put("data", indicatorFinder.countIndicator(queryParams));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    @RequestMapping("/children.json")
    @ResponseBody
    public Object getIndicatorList(String id,
                                      String exclude,
                                      HttpServletRequest request) {
        try {
            List<Indicator> indicators = null;
            if (StringUtils.isBlank(id)) {
//                id = SecurityUtils.currentUser().getOrganId();
//                Indicator org = entityManager.find(Indicator.class, id);
                indicators = indicatorFinder.getIndicatorByDepth(0);
//                indicators = new ArrayList<Indicator>();
//                indicators.add(org);
            }
            else {
                if (StringUtils.isEmpty(exclude)) {
                    indicators = indicatorFinder.getIndicatorChildren(id);
                }
                else {
                    indicators = indicatorFinder.getIndicatorChildren(id,
                                                                               exclude);
                }
            }
            
            List<IndicatorTreeNodeDto> indicatorDtos = new ArrayList<IndicatorTreeNodeDto>();
            for (Indicator indicator : indicators) {
                indicatorDtos.add(IndicatorTreeNodeDto.from(indicator,
                                                                  request));
            }
            
            // map.put("data", indicatorDtos);
            // map.put("succeed", Boolean.TRUE);
            // List<IndicatorTreeNodeDto> dtos = new
            // ArrayList<IndicatorTreeNodeDto>();
            // IndicatorTreeNodeDto a = new IndicatorTreeNodeDto();
            // a.setTitle("test");
            // dtos.add(a);
            return JsonUtils.succeedMap(indicatorDtos);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/list.json")
    @ResponseBody
    public Object getIndicatorList(IndicatorQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            List<Map> indicators = indicatorFinder.getIndicatorMapList(queryParams,
                                                                                queryParams.getStart(),
                                                                                queryParams.getLimit());
            
            map.put("data", indicators);
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        return map;
    }
    
    @RequestMapping("/ourCount.json")
    @ResponseBody
    public Object getOurIndicatorCount(IndicatorQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        try {
            return JsonUtils.succeedMap(indicatorFinder.countOurIndicator(queryParams));
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/ourList.json")
    @ResponseBody
    public Object getOurIndicatorList(IndicatorQueryParameter queryParams) {
        queryParams = initOrganParameterByRole(queryParams);
        try {
            List<Map> indicators = indicatorFinder.getOurIndicatorMapList(queryParams,
                                                                                   queryParams.getStart(),
                                                                                   queryParams.getLimit());
            return JsonUtils.succeedMap(indicators);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    private IndicatorQueryParameter initOrganParameterByRole(IndicatorQueryParameter queryParams) {
        if (queryParams == null) {
            queryParams = new IndicatorQueryParameter();
        }
        if (StringUtils.isEmpty(queryParams.getAncestorId())) {
            queryParams.setAncestorId(SecurityUtils.currentUser().getOrganId());
        }
        
        return queryParams;
    }
    
    @RequestMapping("/detail.do")
    public String getIndicatorDetail(String id, ModelMap map) {
        try {
            
            map.put("data",
                    IndicatorDto.from(indicatorFinder.getIndicator(id)));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            JsonUtils.failedMap(e.getMessage());
        }
        return "indicator/detail";
    }
    
    @RequestMapping("/detail.json")
    @ResponseBody
    public Object getIndicatorDetail(String id) {
        if (StringUtils.isEmpty(id)) {
            // 得到当前用户的指标项
            UserDto user = SecurityUtils.currentUser();
            if (user == null) {
                return JsonUtils.failedMap("未找到当前用户！");
            }
            id = user.getOrganId();
        }
        
        try {
            IndicatorDto dto = IndicatorDto.from(indicatorFinder.getIndicator(id));
            return JsonUtils.succeedMap(dto);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/edit.do")
    public String prepareEditIndicator(String id, ModelMap map) {
        if (StringUtils.isEmpty(id)) {
            return "indicator/detail";
        }
        map.put("data",
                IndicatorDto.from(indicatorFinder.getIndicatorMap(id)));
        return "indicator/detail";
    }
    
    @RequestMapping("/save.json")
    @ResponseBody
    public Object saveIndicator(IndicatorDto dto) {
//        Map map = new HashMap();
//        try {
//            map.put("data",
//                    IndicatorDto.from(indicatorService.saveIndicator(IndicatorDto.to(dto, entityManager))));
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//        return map;
    	try {
			return JsonUtils.succeedMap(IndicatorDto.from(indicatorService.saveIndicator(IndicatorDto.to(dto, entityManager))));
		} catch (Exception e) {
			logger.error(e, e);
			return JsonUtils.failedMap(e.getMessage());
		}
    }
    
    @RequestMapping("/delete.json")
    @ResponseBody
    public Object removeIndicator(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                throw new IllegalArgumentException("指标项ID为空！");
            }
            
            Indicator organ = entityManager.find(Indicator.class, id);
            if (null == organ) {
                return JsonUtils.succeedMap(null);
            }
            
            if (organ.getParent() == null) {
                throw new RuntimeException("不能删除顶级指标项！");
            }
            
            if (!StringUtils.isEmpty(organ.getSourceSystem())) {
                throw new RuntimeException("不能删除同步自其他系统的指标项！");
            }
            
            indicatorService.deleteIndicator(id);
            return JsonUtils.succeedMap(null);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
//    // resource[type='menu']
//    @RequestMapping("/menu/count.json")
//    @ResponseBody
//    public Object getMenuCount(ResourceQueryParameter queryParams) {
//        if (queryParams == null) {
//            queryParams = new ResourceQueryParameter();
//        }
//        queryParams.setType("menu");
//        Map map = new HashMap();
//        try {
//            map.put("data", indicatorService.getResourceCount());
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//        
//        return map;
//    }
//    
//    @RequestMapping("/menu/children.json")
//    @ResponseBody
//    public Object getMenuList(String id) {
//        Map map = new HashMap();
//        try {
//            List<Resource> menus = indicatorService.getResourceChildren(id);
//            
//            List<ResourceTreeNodeDto> menuDtos = new ArrayList<ResourceTreeNodeDto>();
//            for (Resource menu : menus) {
//                menuDtos.add(ResourceTreeNodeDto.from(menu));
//            }
//            
//            map.put("data", menuDtos);
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//        
//        return map;
//    }
//    
//    @RequestMapping("/menu/permission/children.json")
//    @ResponseBody
//    public Object getMenuPermissionList(String id, String roleId) {
//        try {
//            // List<Map> menus =
//            // indicatorService.getMenuPermissionChildren(id,
//            // roleId);
//            List<Map> menus = indicatorService.getMenuOperationPermissionChildren(id,
//                                                                                     roleId);
//            
//            List<PermissionTreeNodeDto> menuDtos = new ArrayList<PermissionTreeNodeDto>();
//            for (Map menu : menus) {
//                menuDtos.add(PermissionTreeNodeDto.from(menu));
//            }
//            
//            return JsonUtils.succeedMap(menuDtos);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
//    
//    @RequestMapping("/role/permission/save.json")
//    @ResponseBody
//    public Object saveMenuPermission(String roleId, String data) {
//        try {
//            List menuPermissions = JsonUtils.parseList(data);
//            menuPermissions = indicatorService.saveMenuPermission(roleId,
//                                                                     menuPermissions);
//            
//            return JsonUtils.succeedMap(menuPermissions);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
//    
//    @RequestMapping("/menu/list.json")
//    @ResponseBody
//    public Object getMenuList(ResourceQueryParameter queryParams) {
//        if (queryParams == null) {
//            queryParams = new ResourceQueryParameter();
//        }
//        queryParams.setType("menu");
//        Map map = new HashMap();
//        try {
//            List<Resource> menus = indicatorService.getResourceList();
//            
//            List<ResourceDto> menuDtos = new ArrayList<ResourceDto>();
//            for (Resource menu : menus) {
//                menuDtos.add(ResourceDto.from(menu));
//            }
//            
//            map.put("data", menuDtos);
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            map.put("succeed", Boolean.FALSE);
//            map.put("message", e.getMessage());
//        }
//        
//        return map;
//    }
//    
//    @RequestMapping("/menu/detail.do")
//    public String getMenuDetail(String id, ModelMap map) {
//        try {
//            map.put("data",
//                    ResourceDto.from(indicatorService.getResource(id)));
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            map.put("succeed", Boolean.FALSE);
//            map.put("message", e.getMessage());
//        }
//        return "menu/detail";
//    }
//    
//    @RequestMapping("/menu/detail.json")
//    @ResponseBody
//    public Object getResourceDetail(String id) {
//        Map map = new HashMap();
//        try {
//            map.put("data",
//                    ResourceDto.from(indicatorService.getResource(id)));
//            map.put("succeed", Boolean.TRUE);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            map.put("succeed", Boolean.FALSE);
//            map.put("message", e.getMessage());
//        }
//        return map;
//    }
    
//    @RequestMapping("/log/count.json")
//    @ResponseBody
//    public Object getLogCount(OperateLogQueryParameter parameter) {
//        parameter = initLogParameterByRole(parameter);
//        try {
//            int count = indicatorFinder.countOperateLog(parameter);
//            return JsonUtils.succeedMap(count);
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
//    
//    @RequestMapping("/log/list.json")
//    @ResponseBody
//    public Object getLogList(OperateLogQueryParameter parameter) {
//        parameter = initLogParameterByRole(parameter);
//        try {
//            List<Map> list = indicatorFinder.listOperateLog(parameter);
//            return JsonUtils.succeedMap(OperateLogDto.from(list));
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
//    
//    private OperateLogQueryParameter initLogParameterByRole(OperateLogQueryParameter queryParameter) {
//        if (queryParameter == null) {
//            queryParameter = new OperateLogQueryParameter();
//        }
//        
//        if (StringUtils.areBlank(queryParameter.getUserId(),
//                                 queryParameter.getOrganId())) {
//            queryParameter.setOrganId(SecurityUtils.currentUser().getOrganId());
//        }
//        return queryParameter;
//    }
    
    
///////////////////////////////////////////////////////////////////
    
    @RequestMapping("/value/count.json")
    @ResponseBody
    public Object getIndicatorValueCount(IndicatorValueQueryParameter queryParams) {
        if (queryParams == null) {
            queryParams = new IndicatorValueQueryParameter();
        }
        Map map = new HashMap();
        try {
            map.put("data", indicatorFinder.countIndicatorValue(queryParams));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    @RequestMapping("/value/list.json")
    @ResponseBody
    public Object getIndicatorValueList(IndicatorValueQueryParameter queryParams) {
        if (queryParams == null) {
            queryParams = new IndicatorValueQueryParameter();
        }
        Map map = new HashMap();
        try {
            List<Map> users = indicatorFinder.getIndicatorValueMapList(queryParams,
                                                                queryParams.getStart(),
                                                                queryParams.getLimit());
            
            map.put("data", users);
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    @RequestMapping("/value/excel.do")
    public Object exportIndicatorValueList(IndicatorValueQueryParameter queryParams, ModelMap map) {
        queryParams = initIndicatorValueParameterByRole(queryParams);
        queryParams.setLimit(Integer.MAX_VALUE);
        List<Map> users = new ArrayList<Map>();
//        		indicatorFinder.listIndicatorValueWithRoles(queryParams);
        map.put("users", users);
        
        return "indicator/value/excel";
    }
    
    @RequestMapping("/value/list.do")
    public Object getIndicatorValueList(ModelMap map) {
//        RoleQueryParameter queryParameter = new RoleQueryParameter();
//        List<Role> roles = indicatorFinder.getRoleList(queryParameter,
//                                                          0,
//                                                          Integer.MAX_VALUE);
//        map.put("roles", roles);
        return "indicator/value/list";
    }
    
    @RequestMapping("/value/ourCount.json")
    @ResponseBody
    public Object getOurIndicatorValueCount(IndicatorValueQueryParameter queryParams) {
        queryParams = initIndicatorValueParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            map.put("data", indicatorFinder.countIndicatorValueWithRoles(queryParams));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    @RequestMapping("/value/ourList.json")
    @ResponseBody
    public Object getOurIndicatorValueList(IndicatorValueQueryParameter queryParams) {
        queryParams = initIndicatorValueParameterByRole(queryParams);
        Map map = new HashMap();
        try {
            List<Map> users = indicatorFinder.listIndicatorValueWithRoles(queryParams);
            
            map.put("data", users);
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        
        return map;
    }
    
    private IndicatorValueQueryParameter initIndicatorValueParameterByRole(IndicatorValueQueryParameter queryParameter) {
        if (queryParameter == null) {
            queryParameter = new IndicatorValueQueryParameter();
        }
        
//        if (StringUtils.isBlank(queryParameter.getOrganId())) {
//            queryParameter.setOrganId(SecurityUtils.currentUser().getOrganId());
//        }
        return queryParameter;
    }
    
    @RequestMapping("/value/edit.do")
    public String prepareEditIndicatorValue(String id, ModelMap map) {
        
        if (StringUtils.isEmpty(id)) {
            IndicatorValueDto dto = new IndicatorValueDto();
            dto.setEnabled(true);
            map.put("data", dto);
            return "indicator/value/new";
        }
        map.put("data", IndicatorValueDto.from(indicatorFinder.getIndicatorValueMap(id)));
        return "indicator/value/edit";
    }
    
    @RequestMapping("/value/detail.do")
    public Object getIndicatorValueDetail(String id, ModelMap map) {
        try {
            map.put("data", IndicatorValueDto.from(indicatorFinder.getIndicatorValue(id)));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        return "indicator/value/detail";
    }
    
    @RequestMapping("/value/detail.json")
    @ResponseBody
    public Object getIndicatorValueDetail(String id) {
        Map map = new HashMap();
        if (StringUtils.isEmpty(id)) {
            map.put("succeed", Boolean.FALSE);
            map.put("message", "id不能为空！");
            return map;
        }
        try {
            map.put("data", IndicatorValueDto.from(indicatorFinder.getIndicatorValue(id)));
            map.put("succeed", Boolean.TRUE);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
        return map;
    }
    
    @RequestMapping("/value/save.json")
    @ResponseBody
    public Object saveIndicatorValue(IndicatorValueDto dto) {
        try {
//            if (StringUtils.isEmpty(dto.getId())) {
//                return JsonUtils.succeedMap(IndicatorValueDto.from(indicatorService.saveIndicatorValue(IndicatorValueDto.to(dto,
//                                                                                                 entityManager))));
//            }
        	IndicatorValueDto indicatorValueDto = IndicatorValueDto.from(indicatorService.saveIndicatorValue(IndicatorValueDto.to(dto, entityManager)));
            return JsonUtils.succeedMap(indicatorValueDto);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/value/delete.json")
    @ResponseBody
    public Object removeIndicatorValue(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                throw new IllegalArgumentException("用户ID为空！");
            }
            
            IndicatorValue indicatorValue = entityManager.find(IndicatorValue.class, id);
            if (null == indicatorValue) {
                return JsonUtils.succeedMap(null);
            }
            
            
            indicatorService.deleteIndicatorValue(id);
            return JsonUtils.succeedMap(null);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/value/tree.json")
    @ResponseBody
    public Object getIndicatorValueTree(String id, HttpServletRequest request) {
        try {
            List<TreeNode> nodes = new ArrayList<TreeNode>();
//            if (StringUtils.isBlank(id)) {
//                if (SecurityUtils.isManager()) {
//                    id = SecurityUtils.currentIndicatorValue().getOrganId();
//                    Indicator org = entityManager.find(Indicator.class,
//                                                          id);
//                    nodes.add(IndicatorTreeNodeDto.from(org, request));
//                }
//                else {
//                    nodes.add(IndicatorValueTreeNodeDto.from(SecurityUtils.currentUser(),
//                                                   request));
//                }
//            }
//            else {
//                List<Indicator> organs = indicatorFinder.getIndicatorChildren(id);
//                List<IndicatorValue> users = indicatorFinder.getIndicatorValueListByOrgan(id);
//                for (Indicator Indicator : organs) {
//                    nodes.add(IndicatorTreeNodeDto.from(Indicator,
//                                                           request));
//                }
//                for (IndicatorValue user : users) {
//                    nodes.add(IndicatorValueTreeNodeDto.from(user, request));
//                }
//            }
            return JsonUtils.succeedMap(nodes);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/value/phone.json")
    @ResponseBody
    public Object getIndicatorValuePhones(String userId) {
        try {
            List<Phone> phones = phoneQuery.list(userId);
            return JsonUtils.succeedMap(phones);
        }
        catch (Exception e) {
            logger.error(e, e);
            return JsonUtils.failedMap(e.getMessage());
        }
    }
    
    @RequestMapping("/value/phones.do")
    public String userPhonesPage() {
        return "indicator/value/phones";
    }
    
//    @RequestMapping("/value/phone/list.json")
//    @ResponseBody
//    public Object listIndicatorValuePhones(PhoneQueryParameter parameter) {
//        parameter = initPhoneParameterByRole(parameter);
//        try {
//            return JsonUtils.succeedMap(phoneQuery.list(parameter));
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
//    
//    @RequestMapping("/value/phone/count.json")
//    @ResponseBody
//    public Object countIndicatorValuePhones(PhoneQueryParameter parameter) {
//        parameter = initPhoneParameterByRole(parameter);
//        try {
//            return JsonUtils.succeedMap(phoneQuery.count(parameter));
//        }
//        catch (Exception e) {
//            logger.error(e, e);
//            return JsonUtils.failedMap(e.getMessage());
//        }
//    }
    
//    private PhoneQueryParameter initPhoneParameterByRole(PhoneQueryParameter queryParams) {
//        if (queryParams == null) {
//            queryParams = new PhoneQueryParameter();
//        }
//        if (StringUtils.areEmpty(queryParams.getIndicatorValueId(),
//                                 queryParams.getOrganId())) {
//            queryParams.setOrganId(SecurityUtils.currentIndicatorValue().getOrganId());
//        }
//        
//        return queryParams;
//    }
    @RequestMapping("/value/import.json")
    @ResponseBody
    @Transactional
    public Object importIndicatorValue(HttpServletRequest request) throws Exception {  
    	String filePath = request.getRealPath("/指标项.txt");
    	File file = null;
    	FileInputStream in = null;
		InputStreamReader reader = null;
		BufferedReader br = null;
		try {
			file = new File(filePath);
			in = new FileInputStream(file);
			reader = new InputStreamReader(in,"UTF-8");
			br = new BufferedReader(reader);
			String content = br.readLine();
			List<IndicatorValue> valList = new ArrayList<IndicatorValue>();
			Date date = new Date();
			User creator = entityManager.find(User.class, SecurityUtils.currentUserId());
			while (content != null) {
				String[] ss = content.split("_");
				if (ss.length == 2 && !StringUtils.isBlank(ss[0])) {
					Indicator ind = (Indicator) entityManager.findFirst("from Indicator i where i.boundProperties=?", new String[]{ss[0]});
					for(String s : ss[1].split(",")){
						IndicatorValue val = new IndicatorValue();
						val.setIndicator(ind);
						val.setName(s);
						val.setCreator(creator);
						val.setCreateDateTime(date);
						valList.add(val);
					}
				}
				content = br.readLine();
			}
			entityManager.save(valList);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizException(e);
		}finally{
			if(null!=br){try {br.close();}catch(Exception ignore){}}
			if(null!=reader){try {reader.close();}catch(Exception ignore){}}
			if(null!=in){try {in.close();}catch(Exception ignore){}}
			file = null;
		}
    	
    	return null;
    }
}
